import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getCurrentUser } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(null)
  const loading = ref(false)

  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 登录
  const login = async (username, password) => {
    try {
      loading.value = true
      const response = await apiLogin({ username, password })

      if (response.data.code === 200) {
        const { token: newToken, ...userInfo } = response.data.data
        token.value = newToken
        user.value = userInfo

        localStorage.setItem('token', newToken)

        ElMessage.success('登录成功')
        return { success: true }
      } else {
        ElMessage.error(response.data.message || '登录失败')
        return { success: false, message: response.data.message }
      }
    } catch (error) {
      const message = error.response?.data?.message || error.message || '登录失败'
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    ElMessage.success('已退出登录')
  }

  // 检查认证状态
  const checkAuth = async () => {
    if (!token.value) {
      console.log('checkAuth: 没有token，返回false')
      return false
    }

    try {
      console.log('checkAuth: 获取用户信息...')
      // 直接调用 /auth/me 来验证token
      // 如果token无效，会返回401错误
      const userResponse = await getCurrentUser()
      if (userResponse.data.code === 200) {
        user.value = userResponse.data.data
        console.log('checkAuth: 认证检查成功', { username: user.value.username, role: user.value.role })
        return true
      } else {
        console.log('checkAuth: 获取用户信息失败', userResponse.data)
        console.log('checkAuth: 清除认证信息')
        logout()
        return false
      }
    } catch (error) {
      // 如果是401错误，说明token无效
      if (error.response?.status === 401) {
        console.log('checkAuth: token无效或已过期', error.response.status)
      } else {
        console.error('checkAuth: 认证检查异常', error)
      }
      console.log('checkAuth: 清除认证信息')
      logout()
      return false
    }
  }

  // 获取用户信息
  const getUserInfo = () => {
    return user.value
  }

  // 新增：应用启动时初始化认证状态
  const initAuth = async () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken && !token.value) {
      console.log('initAuth: 从localStorage恢复token')
      token.value = savedToken
      return await checkAuth()
    }
    return false
  }

  return {
    token,
    user,
    loading,
    isAuthenticated,
    login,
    logout,
    checkAuth,
    getUserInfo,
    initAuth
  }
})
